package com.lianniu.mgr.login.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.lianniu.mgr.util.StringUtil;
import com.lianniu.redis.RedisUtils;

public class LoginFilter implements Filter {
  private final static Logger logger = Logger.getLogger(LoginFilter.class);
  private static String[] whiteList;
  private static RedisUtils redisUtils;
  private final static int TIME=3600*24;
  
  
  public static void setRedisUtils(RedisUtils redisUtils) {
    LoginFilter.redisUtils = redisUtils;
  }

  
  public void init(FilterConfig filterConfig) throws ServletException {
    String whiteListStr = filterConfig.getInitParameter("whiteList");
    if (!StringUtil.isEmpty(whiteListStr)) {
      whiteList = whiteListStr.split("\\|");
    }

  }

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    String url = req.getRequestURI().toString();
    logger.info("LoginFilter doFilter url:" + url);
    if (whiteList == null) {
      chain.doFilter(request, response);
      return;
    }
    for (String whiteUrl : whiteList) {
      if (url.contains(whiteUrl)) {
        chain.doFilter(request, response);
        return;
      }
    }
    if(true){
    	chain.doFilter(request, response);
        return;
    }
    String token =req.getParameter("token");
    logger.info("LoginFilter doFilter token:" + token);

    if (!StringUtil.isEmpty(token) && !StringUtil.isEmpty(redisUtils.get("saasMgr:"+token))) {
//      String username=redisUtils.get("saasMgr:"+token);
//      //token匹配用户名
//      if(StringUtil.isEmpty(username)){
//        req.getRequestDispatcher("/rest/loginCheckFail.do").forward(request, response);
//        return;
//      }
//      //token校验
//      String getToken=redisUtils.get("saasMgr:"+username);
//      if(!getToken.equals(token)){
//        req.getRequestDispatcher("/rest/loginCheckFail.do").forward(request, response);
//        return;
//      }
      
//      redisUtils.setTimeOut("saasMgr:" + token, username, TIME);
//      redisUtils.setTimeOut("saasMgr:"+username, token, TIME);
      
      redisUtils.expire("saasMgr:" + token, TIME);
//      redisUtils.expire("saasMgr:" + username, TIME);
      
      chain.doFilter(request, response);
      return;
    }
    req.getRequestDispatcher("/rest/loginCheckFail.do").forward(request, response);

  }

  public void destroy() {

  }

}
